package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.feigns.BehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dto.HistorySearchDTO;
import com.heima.model.search.dto.UserSearchDTO;
import com.heima.model.search.pojos.ApUserSearch;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.threadlocal.AppThreadLocalUtils;
import com.heima.search.service.ApUserSearchService;
import javafx.scene.shape.Circle;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    BehaviorFeign behaviorFeign;
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    public void insert(UserSearchDTO userSearchDto) {
        //参数校验
        if (userSearchDto.getSearchWords() == null || userSearchDto.getSearchWords().equals("")) {
            log.error("保存历史记录时出错,原因搜索关键字不存在");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断当前是否有用户登录
        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> behaviorResponse = null;
        if (user == null){
            //当前没有用户登录
            behaviorResponse = behaviorFeign.findByUserIdOrEquipmentId(null, userSearchDto.getEquipmentId());
        }else {
            behaviorResponse = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), null);
        }
        //判断调用是否成功
        if (!behaviorResponse.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApBehaviorEntry apBehaviorEntry = behaviorResponse.getData();
        if (apBehaviorEntry==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //查询当前搜索关键词是否存在
        ApUserSearch one = mongoTemplate.findOne(Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId())
                .and("keyword").is(userSearchDto.getSearchWords())), ApUserSearch.class);
        //判断当前搜索词是否存在
        if (one != null){
            //存在更新创建时间
            one.setCreatedTime(new Date());
            mongoTemplate.save(one);
            return;
        }else{
            //不存在则创建
            ApUserSearch apUserSearch = new ApUserSearch();
            apUserSearch.setEntryId(apBehaviorEntry.getId());
            apUserSearch.setKeyword(userSearchDto.getSearchWords());
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
        }
    }

    /**
     * 查询搜索记录
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult findUserSearch(UserSearchDTO userSearchDto) {
        //判断用户是否登录  并通过feign查询实体
        ApUser user = AppThreadLocalUtils.getUser();
        ResponseResult<ApBehaviorEntry> apBehaviorEntry = null;
        if (user != null){
            apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(user.getId(), null);
        }else{
            //判断设备Id是否存在
            if (userSearchDto.getEquipmentId() != null){
                apBehaviorEntry = behaviorFeign.findByUserIdOrEquipmentId(null, userSearchDto.getEquipmentId());
            }else{
                log.error("设备id不存在");
                CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
            }
        }
        log.info("获取到的数据{}",apBehaviorEntry.getData());
        //判断实体数据是否存在
        if (apBehaviorEntry == null){
            log.error("feign调用查询实体微服务时数据为空");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApBehaviorEntry entry = apBehaviorEntry.getData();
        //根据实体id查询用户的搜索记录
        List<ApUserSearch> searches = mongoTemplate.find(Query.query(Criteria.where("entryId").is(entry.getId()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(10), ApUserSearch.class);

        return ResponseResult.okResult(searches);
    }

    @Override
    public ResponseResult delUserSearch(HistorySearchDTO historySearchDto) {
        //根据id删除
        if (historySearchDto.getId() == null){
            log.error("需要删除的数据id不存在");
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Query id = Query.query(Criteria.where("_id").is(historySearchDto.getId()));

        mongoTemplate.remove(id,ApUserSearch.class);
        return ResponseResult.okResult();
    }
}
